package com.lanchong.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.lanchong.config.AlipayConfig;
import com.lanchong.pojo.GoodsVo;
import com.lanchong.pojo.OrderDetail;
import com.lanchong.pojo.OrderInfo;
import com.lanchong.pojo.User;
import com.lanchong.result.CodeMsg;
import com.lanchong.result.Result;
import com.lanchong.service.GoodsService;
import com.lanchong.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;

/**
 * @program: SeckillProject
 * @description: 订单表现层
 **/
@Slf4j
@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private GoodsService goodsService;
    @Resource
    private AlipayConfig alipayConfig;


    @RequestMapping("/detail")
    @ResponseBody
    public Result<OrderDetail> info(User user, @RequestParam("orderId") long orderId) {
        if (user == null) {
            return Result.error(CodeMsg.SESSION_ERROR);
        }
        OrderInfo orderInfo = orderService.getByOrderId(orderId);
        if(orderInfo == null) {
            return Result.error(CodeMsg.ORDER_NOT_EXIST);
        }

        long goodsId = orderInfo.getGoodsId();
        GoodsVo goods = goodsService.getGoodsVoById(goodsId);

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrder(orderInfo);
        orderDetail.setGoods(goods);
        return Result.success(orderDetail);
    }
    @GetMapping("/selectPayType")
    public String selectPayType(HttpServletRequest request, @RequestParam("orderId") long orderId, HttpSession session) {
//        User user = (User) session.getAttribute("user_id");
//        OrderInfo order = judgeOrderUserId(orderId,user.getId());
        OrderInfo order = orderService.getByOrderId(orderId);
        request.setAttribute("orderId", orderId);
        request.setAttribute("goodsPrice", order.getGoodsPrice());
        return "mall/pay-select";
    }

    @GetMapping("/payPage")
    public String payOrder(HttpServletRequest request, @RequestParam("orderId") long orderId, HttpSession session) throws UnsupportedEncodingException {
//        User user = (User) session.getAttribute("user_id");
//        OrderInfo order = judgeOrderUserId(orderId,user.getId());
        OrderInfo order = orderService.getByOrderId(orderId);
        request.setAttribute("orderId", orderId);
        request.setAttribute("goodsPrice", order.getGoodsPrice());
        request.setCharacterEncoding("utf-8");
        // 初始化
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGateway(), alipayConfig.getAppId(),
                alipayConfig.getRsaPrivateKey(), alipayConfig.getFormat(), alipayConfig.getCharset(), alipayConfig.getAlipayPublicKey(),
                alipayConfig.getSigntype());
        // 创建API对应的request
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//            // 在公共参数中设置回调和通知地址
//            String url = "localhost" + request.getContextPath();
//            alipayRequest.setReturnUrl(url + "/returnOrders/" + order.getId() + "/" + user.getId() );
//            alipayRequest.setNotifyUrl(url + "/paySuccess?id=" + order.getId());

        // 填充业务参数

        // 必填
        // 商户订单号，需保证在商户端不重复
        String out_trade_no = String.valueOf(order.getId());
        // 销售产品码，与支付宝签约的产品码名称。目前仅支持FAST_INSTANT_TRADE_PAY
        String product_code = "FAST_INSTANT_TRADE_PAY";
        // 订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]。
        String total_amount = order.getGoodsPrice() + "";
        // 订单标题
        String subject = "支付宝测试";

        // 选填
        // 商品描述，可空
        String body = "商品描述";

        alipayRequest.setBizContent("{" + "\"out_trade_no\":\"" + out_trade_no + "\"," + "\"product_code\":\""
                + product_code + "\"," + "\"total_amount\":\"" + total_amount + "\"," + "\"subject\":\"" + subject
                + "\"," + "\"body\":\"" + body + "\"}");
        // 请求
        String form;
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();//调用SDK生成表单
            request.setAttribute("form", form);
        } catch (AlipayApiException e) {

            log.error(e.getMessage(), e);
            ;
        }
        return "mall/alipay";
    }

    /**
     * 判断订单关联用户id和当前登陆用户是否一致
     *
     * @param orderId 订单编号

     * @return 返回订单对象
     */
    private OrderInfo judgeOrderUserId(long orderId ,long userId) {
        OrderInfo order = orderService.getOrderByUserIdOrdersId(orderId,userId);
        // 判断订单userId
        if (order == null ) {
//            throw new BusinessException("当前订单用户异常");
            return null;
        }
        return order;
    }
}
